package com.lanzhou.yuanfen.controller;

import com.lanzhou.yuanfen.config.UploadProperties;
import com.lanzhou.yuanfen.response.ServerResponseResult;
import com.lanzhou.yuanfen.sys.entity.File;
import com.lanzhou.yuanfen.sys.service.IFileService;
import com.lanzhou.yuanfen.util.UploadComponent;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 上传Controller
 *
 * @author Administrator
 */
@Slf4j
@Controller
@RequestMapping("/upload/")
public class UploadController {


    @Resource
    private UploadComponent uploadComponent;

    @Resource
    private IFileService fileService;

    @Resource
    private UploadProperties uploadProperties;

    private static final String WANG = "wang";


    /**
     * 上资源: 上传name默认值就是 file
     *
     * @param request 请求
     * @return 文件对象, 存储文件信息
     */
    @ResponseBody
    @PostMapping("resource")
    public ServerResponseResult uploadResource(HttpServletRequest request) {
        MultipartFile file;
        File f = new File();
        try {
            MultipartHttpServletRequest mreQuest = (MultipartHttpServletRequest) request;
            file = mreQuest.getFile("file");
            assert file != null;
            buildFile(file, f);
            String downPath = uploadComponent.uploadFile(file, null);
            if (downPath == null) {
                return ServerResponseResult.fail("上传失败, 请联系管理员");
            }
            f.setRemoteUrl(uploadProperties.getDownloadUrl());
            f.setFilePath(downPath);
            fileService.save(f);
        } catch (Exception e) {
            log.error("上传文件失败, 请稍后重试!!", e);
            return ServerResponseResult.fail("上传失败, 请联系管理员");
        }
        return ServerResponseResult.success(f);
    }


    /**
     * 上资源: 上传name默认值就是 file
     *
     * @param request 请求
     * @return 文件对象, 存储文件信息
     */
    @ResponseBody
    @PostMapping("wangImg")
    public WangImgResponse wangImg(HttpServletRequest request) {
        WangImgResponse response = new WangImgResponse();
        response.errno = 0;
        MultipartFile file;
        File f = new File();
        try {
            MultipartHttpServletRequest mreQuest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> multiFileMap = mreQuest.getMultiFileMap();
            Set<String> keys = multiFileMap.keySet();
            file = mreQuest.getFile(keys.iterator().next());
            assert file != null;
            String fileName = buildFile(file, f);
            String downPath = uploadComponent.uploadFile(file, WANG);
            if (downPath == null) {
                response.errno = 201;
                log.info("上传失败, 请联系管理员: [ {} ]", fileName);
                return response;
            }
            f.setRemoteUrl(uploadProperties.getDownloadUrl());
            f.setFilePath(downPath);
            fileService.save(f);
            List<String> data = new ArrayList<>();
            data.add(f.getRemoteUrl() + WANG + "/" + downPath);
            response.data = data;
        } catch (Exception e) {
            response.errno = 201;
            log.error("上传失败, 请联系管理员", e);
            return response;
        }
        return response;
    }

    /**
     * 将资源放在系统File中
     *
     * @param file
     * @param f
     * @return
     */
    private String buildFile(MultipartFile file, File f) {
        String fileName = file.getName();
        f.setSourceName(fileName);
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        f.setFileType(type);
        // 大小以kb计算
        f.setFileSize(file.getSize() / 1024);
        return fileName;
    }


    @Setter
    @Getter
    @ToString
    public static class WangImgResponse {

        /**
         * 返回错误码
         * 即错误代码，0 表示没有错误。
         */
        private Integer errno;

        /**
         * data 是一个数组，返回若干图片的线上地址
         */
        private List<String> data;

    }


}
